import React, { useState, useEffect } from 'react';
import { 
  Card, 
  Descriptions, 
  Tag, 
  Button, 
  Space, 
  Timeline, 
  Comment, 
  Form, 
  Input, 
  message,
  Spin,
  List,
  Typography,
  Avatar,
  Modal,
  Image
} from 'antd';
import { 
  EditOutlined, 
  CheckCircleOutlined, 
  CloseCircleOutlined, 
  ClockCircleOutlined,
  FileOutlined,
  DownloadOutlined,
  UserOutlined,
  EyeOutlined,
  FileImageOutlined,
  VideoCameraOutlined,
  FilePdfOutlined,
  FileWordOutlined,
  FileExcelOutlined,
  FileTextOutlined
} from '@ant-design/icons';
import { useHistory, useParams } from 'react-router-dom';
import api from '../services/api';
import { useUser } from '../contexts/UserContext';

const { TextArea } = Input;
const { Text } = Typography;

const IssueDetailPage = () => {
  const [issue, setIssue] = useState(null);
  const [comments, setComments] = useState([]);
  const [loading, setLoading] = useState(false);
  const [previewVisible, setPreviewVisible] = useState(false);
  const [previewFile, setPreviewFile] = useState(null);
  const [form] = Form.useForm();
  const history = useHistory();
  const { id } = useParams();
  const { user } = useUser();

  // 获取问题详情
  const fetchIssueDetail = async () => {
    setLoading(true);
    try {
      const response = await api.get(`/issues/${id}`);
      setIssue(response.data);
      // 同时获取评论数据
      await fetchComments();
    } catch (error) {
      console.error('获取问题详情失败:', error);
      message.error('获取问题详情失败');
    } finally {
      setLoading(false);
    }
  };

  // 获取评论列表
  const fetchComments = async () => {
    try {
      const response = await api.get(`/comments/issue/${id}`);
      setComments(response.data);
    } catch (error) {
      console.error('获取评论失败:', error);
      // 如果获取失败，保持当前评论状态不变
    }
  };

  useEffect(() => {
    fetchIssueDetail();
  }, [id]);

  const handleAddComment = async (values) => {
    try {
      // 调用真实的API添加评论
      await api.post(`/comments/issue/${id}`, {
        content: values.content
      });
      
      form.resetFields();
      message.success('评论添加成功');
      
      // 重新获取评论列表
      await fetchComments();
    } catch (error) {
      console.error('添加评论失败:', error);
      message.error('添加评论失败');
    }
  };

  const handleStartProcessing = async () => {
    try {
      await api.put(`/issues/${id}`, { status: 'in_progress' });
      message.success('问题状态已更新');
      fetchIssueDetail(); // 重新获取问题详情
    } catch (error) {
      console.error('更新问题状态失败:', error);
      message.error('更新问题状态失败');
    }
  };

  const handleMarkAsResolved = async () => {
    try {
      await api.put(`/issues/${id}`, { status: 'resolved' });
      message.success('问题状态已更新');
      fetchIssueDetail(); // 重新获取问题详情
    } catch (error) {
      console.error('更新问题状态失败:', error);
      message.error('更新问题状态失败');
    }
  };

  const handleReject = async () => {
    try {
      await api.put(`/issues/${id}`, { status: 'rejected' });
      message.success('问题状态已更新');
      fetchIssueDetail(); // 重新获取问题详情
    } catch (error) {
      console.error('更新问题状态失败:', error);
      message.error('更新问题状态失败');
    }
  };

  if (loading) {
    return <Spin size="large" style={{ display: 'block', margin: '50px auto' }} />;
  }

  if (!issue) {
    return <div>问题不存在</div>;
  }

  const statusMap = {
    open: { text: '待处理', color: 'blue' },
    in_progress: { text: '处理中', color: 'orange' },
    resolved: { text: '已解决', color: 'green' },
    closed: { text: '已关闭', color: 'gray' },
    rejected: { text: '已驳回', color: 'red' }
  };

  const { text: statusText, color: statusColor } = statusMap[issue.status];

  // 文件类型检测
  const getFileType = (name) => {
    if (!name) return 'unknown';
    const extension = name.split('.').pop().toLowerCase();
    
    if (['jpg', 'jpeg', 'png', 'gif', 'bmp', 'webp'].includes(extension)) {
      return 'image';
    }
    if (['mp4', 'avi', 'mkv', 'mov', 'wmv', 'flv'].includes(extension)) {
      return 'video';
    }
    if (['pdf'].includes(extension)) {
      return 'pdf';
    }
    if (['txt', 'md', 'log'].includes(extension)) {
      return 'text';
    }
    if (['doc', 'docx', 'xls', 'xlsx', 'ppt', 'pptx'].includes(extension)) {
      return 'office';
    }
    return 'unknown';
  };

  // 获取文件图标
  const getFileIcon = (name) => {
    const extension = name ? name.split('.').pop().toLowerCase() : '';
    
    if (['jpg', 'jpeg', 'png', 'gif', 'bmp', 'webp'].includes(extension)) {
      return <FileImageOutlined style={{ fontSize: '16px', color: '#52c41a' }} />;
    }
    if (['mp4', 'avi', 'mkv', 'mov', 'wmv', 'flv'].includes(extension)) {
      return <VideoCameraOutlined style={{ fontSize: '16px', color: '#722ed1' }} />;
    }
    if (['pdf'].includes(extension)) {
      return <FilePdfOutlined style={{ fontSize: '16px', color: '#ff4d4f' }} />;
    }
    if (['doc', 'docx'].includes(extension)) {
      return <FileWordOutlined style={{ fontSize: '16px', color: '#1890ff' }} />;
    }
    if (['xls', 'xlsx'].includes(extension)) {
      return <FileExcelOutlined style={{ fontSize: '16px', color: '#52c41a' }} />;
    }
    if (['txt', 'md'].includes(extension)) {
      return <FileTextOutlined style={{ fontSize: '16px', color: '#8c8c8c' }} />;
    }
    
    return <FileOutlined style={{ fontSize: '16px', color: '#8c8c8c' }} />;
  };

  // 文件预览函数
  const handlePreview = (file) => {
    const fileType = getFileType(file.original_filename);
    
    if (fileType === 'image' || fileType === 'video' || fileType === 'pdf' || fileType === 'text') {
      setPreviewFile({ 
        ...file, 
        fileType,
        path: `http://localhost:8001${file.file_url}`,
        name: file.original_filename
      });
      setPreviewVisible(true);
    } else {
      message.info('该文件类型暂不支持预览，请下载后查看');
    }
  };

  // 文件下载函数
  const handleDownload = (file) => {
    const link = document.createElement('a');
    link.href = `http://localhost:8001${file.file_url}`;
    link.download = file.original_filename;
    link.target = '_blank';
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);
  };

  // 渲染预览内容
  const renderPreviewContent = () => {
    if (!previewFile) return null;
    
    switch (previewFile.fileType) {
      case 'image':
        return (
          <Image
            width="100%"
            src={previewFile.path}
            alt={previewFile.name}
          />
        );
      case 'video':
        return (
          <video 
            width="100%" 
            controls 
            style={{ maxHeight: '400px' }}
          >
            <source src={previewFile.path} type="video/mp4" />
            您的浏览器不支持视频播放。
          </video>
        );
      case 'pdf':
        return (
          <iframe 
            src={previewFile.path} 
            width="100%" 
            height="500px"
            style={{ border: 'none' }}
            title={previewFile.name}
          >
            您的浏览器不支持PDF预览。
          </iframe>
        );
      case 'text':
        return (
          <div style={{ 
            padding: '16px', 
            backgroundColor: '#f5f5f5', 
            borderRadius: '4px',
            maxHeight: '400px',
            overflow: 'auto'
          }}>
            <Typography.Paragraph>
              文本文件预览功能开发中...
            </Typography.Paragraph>
          </div>
        );
      default:
        return <div>暂不支持该文件类型的预览</div>;
    }
  };

  // 渲染评论的递归函数
  const renderComment = (comment) => {
    return (
      <Comment
        key={comment.id}
        author={comment.author_username}
        avatar={<Avatar icon={<UserOutlined />} />}
        content={comment.content}
        datetime={new Date(comment.created_at).toLocaleString()}
      >
        {comment.replies && comment.replies.length > 0 && (
          <div>
            {comment.replies.map(reply => renderComment(reply))}
          </div>
        )}
      </Comment>
    );
  };

  return (
    <div>
      <Space style={{ marginBottom: 16 }}>
        <Button icon={<EditOutlined />} onClick={() => history.push(`/issues/${id}/edit`)}>
          编辑
        </Button>
        {issue.status === 'open' && (
          <Button 
            icon={<CheckCircleOutlined />} 
            type="primary" 
            onClick={handleStartProcessing}
          >
            开始处理
          </Button>
        )}
        {issue.status === 'in_progress' && (
          <Button 
            icon={<CheckCircleOutlined />} 
            type="primary" 
            onClick={handleMarkAsResolved}
          >
            标记为已解决
          </Button>
        )}
        <Button icon={<CloseCircleOutlined />} danger onClick={handleReject}>
          驳回
        </Button>
      </Space>

      <Card title={issue.title} style={{ marginBottom: 16 }}>
        <Descriptions column={2} bordered>
          <Descriptions.Item label="问题ID">{issue.id}</Descriptions.Item>
          <Descriptions.Item label="状态">
            <Tag color={statusColor}>{statusText}</Tag>
          </Descriptions.Item>
          <Descriptions.Item label="类型">
            <Tag color={issue.type === 'customer' ? 'blue' : 'green'}>
              {issue.type === 'customer' ? '客户问题' : '内部问题'}
            </Tag>
          </Descriptions.Item>
          <Descriptions.Item label="分类">{issue.category}</Descriptions.Item>
          <Descriptions.Item label="优先级">
            <Tag color={issue.priority === 'high' ? 'red' : issue.priority === 'medium' ? 'orange' : 'green'}>
              {issue.priority === 'high' ? '高' : issue.priority === 'medium' ? '中' : '低'}
            </Tag>
          </Descriptions.Item>
          <Descriptions.Item label="提交人">{issue.submitter?.username || issue.submitter || '未知'}</Descriptions.Item>
          <Descriptions.Item label="处理人">{issue.assignee?.username || issue.assignee || '未分配'}</Descriptions.Item>
          <Descriptions.Item label="创建时间">{new Date(issue.created_at).toLocaleString()}</Descriptions.Item>
          <Descriptions.Item label="更新时间">{new Date(issue.updated_at).toLocaleString()}</Descriptions.Item>
        </Descriptions>

        <div style={{ marginTop: 24 }}>
          <h3>问题描述</h3>
          <p>{issue.description}</p>
        </div>

        {/* 附件显示 */}
        {issue.attachments && issue.attachments.length > 0 && (
          <div style={{ marginTop: 24 }}>
            <h3>附件</h3>
            <List
              size="small"
              dataSource={issue.attachments}
              renderItem={(item) => {
                const fileType = getFileType(item.original_filename);
                const canPreview = ['image', 'video', 'pdf', 'text'].includes(fileType);
                
                return (
                  <List.Item
                    actions={[
                      canPreview ? (
                        <Button
                          type="link"
                          size="small"
                          icon={<EyeOutlined />}
                          onClick={() => handlePreview(item)}
                        >
                          预览
                        </Button>
                      ) : (
                        <Button type="link" size="small" disabled>
                          预览
                        </Button>
                      ),
                      <Button
                        type="link"
                        size="small"
                        icon={<DownloadOutlined />}
                        onClick={() => handleDownload(item)}
                      >
                        下载
                      </Button>
                    ]}
                  >
                    <List.Item.Meta
                      avatar={getFileIcon(item.original_filename)}
                      title={item.original_filename || '附件文件'}
                      description={
                        <Text type="secondary">
                          {item.file_size ? `大小: ${(item.file_size / 1024).toFixed(2)} KB` : ''}
                          {item.mime_type && ` - 类型: ${item.mime_type}`}
                          {item.created_at && ` - 上传时间: ${new Date(item.created_at).toLocaleString()}`}
                        </Text>
                      }
                    />
                  </List.Item>
                );
              }}
            />
          </div>
        )}

        {issue.similarity_score >= 0.85 && issue.matched_case && (
          <div style={{ marginTop: 24 }}>
            <h3>相似案例推荐</h3>
            <Card size="small">
              <p>
                匹配度: <Tag color="green">{(issue.similarity_score * 100).toFixed(0)}%</Tag>
              </p>
              <p>
                推荐解决方案: 
                <a href={`/cases/${issue.matched_case.id}`} style={{ marginLeft: 8 }}>
                  {issue.matched_case.title}
                </a>
              </p>
            </Card>
          </div>
        )}
      </Card>

      <Card title="处理进度" style={{ marginBottom: 16 }}>
        <Timeline>
          <Timeline.Item dot={<ClockCircleOutlined style={{ fontSize: '16px' }} />}>
            问题创建 {new Date(issue.created_at).toLocaleString()}
          </Timeline.Item>
          {issue.assignee && (
            <Timeline.Item>分配给 {issue.assignee.username || issue.assignee}</Timeline.Item>
          )}
          {issue.status === 'in_progress' && (
            <Timeline.Item>开始处理</Timeline.Item>
          )}
          {issue.status === 'resolved' && (
            <Timeline.Item>问题已解决</Timeline.Item>
          )}
        </Timeline>
      </Card>

      <Card title="评论">
        {comments.map((comment) => renderComment(comment))}

        <Comment
          avatar={<Avatar icon={<UserOutlined />} />}
          content={
            <Form form={form} onFinish={handleAddComment}>
              <Form.Item name="content" rules={[{ required: true, message: '请输入评论内容' }]}>
                <TextArea rows={4} placeholder={user ? `以 ${user.username} 身份发表评论...` : '请输入评论内容...'} />
              </Form.Item>
              <Form.Item>
                <Button htmlType="submit" type="primary">
                  添加评论
                </Button>
              </Form.Item>
            </Form>
          }
        />
      </Card>
      
      {/* 预览Modal */}
      <Modal
        title={`预览: ${previewFile?.name || ''}`}
        visible={previewVisible}
        onCancel={() => setPreviewVisible(false)}
        footer={[
          <Button key="download" icon={<DownloadOutlined />} onClick={() => handleDownload(previewFile)}>
            下载
          </Button>,
          <Button key="close" onClick={() => setPreviewVisible(false)}>
            关闭
          </Button>
        ]}
        width={800}
        centered
      >
        {renderPreviewContent()}
      </Modal>
    </div>
  );
};

export default IssueDetailPage;